﻿using Aspfm.Dal;
using Aspfm.Main;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aspfm.Login
{
    public class Login: Aspfm.Main.IMainController
    {
        public override void MvcController(string active)
        {
            if (active == "login")
            {
                string dbkey = base.RequestDynObj.GetPropertyValueStr("connkey");
                string userno = base.RequestDynObj.GetPropertyValueStr("userid");
                string userpwd = base.RequestDynObj.GetPropertyValueStr("pwd");
                string SHA1_Pwd = MySecurity.EncryptSHA1(userpwd);
                IDbHelper db = Aspfm.Dal.DbFactory.GetDB(dbkey);
                DataSet ds = db.QuerySql("select * from aspfmuser_info where uno=st(0)", userno);
                if (DbFactory.CheckDSHadRow(ds))
                {
                    if (SHA1_Pwd == ds.Tables[0].Rows[0]["upwd"].ToString())
                    {
                        UserIdentity u = new UserIdentity(false);
                        u._uguid = ds.Tables[0].Rows[0]["uguid"].ToString();
                        u._uno = ds.Tables[0].Rows[0]["uno"].ToString();
                        u._uname = ds.Tables[0].Rows[0]["uname"].ToString();
                        u._dept = ds.Tables[0].Rows[0]["dept"].ToString();
                        u._loginType = "";
                        u.SysRoleLevel = ds.Tables[0].Rows[0]["SysRoleLevel"].ToString();
                        SessionTool.Clear();
                        SessionTool.SetUserCookie(u);
                        CacheHelper.SetCache(u.LoginGuid, u, new TimeSpan(0, 5, 0));//缓存5分钟

                        base.ReturnHtml(u.LoginGuid);
                    }
                    else
                    {
                        base.ReturnHtml("error:密码错误。");
                    }
                }
                else
                {
                    base.ReturnHtml("error:没有找到账号。");
                }
            }
            else if (active == "file")
            {
                base.ReturnFile(@"D:\MyWork\MyProject\aspfm\AspfmWeb\AspfmWeb\新建文件夹\对应字段.xlsx");
            }
        }
        public string Logout()
        {
            SessionTool.Clear();
            if (!string.IsNullOrWhiteSpace(User.LoginGuid))
            {
                IDbHelper idb = DbFactory.GetDB();
                Logout(idb, User.LoginGuid);
            }
            return "0";
        }
        public WebResult LoginUser(string uno, string pwd, string logintype)
        {
            SessionTool.Clear();
            if (!string.IsNullOrWhiteSpace(uno) && !string.IsNullOrWhiteSpace(logintype))
            {
                uno = uno.Trim().ToUpper();
                if (LoginHelp.CheckPwdErr(uno))
                {
                    return new WebResult("password_error_5_times_in_one_hours");
                }
                string mPwd = SEncryptPwd(pwd, uno);
                DataRow dr;
                string errmsg = LoginHelp.CheckPwd(uno, mPwd, out dr);
                if (!string.IsNullOrEmpty(errmsg))
                {
                    return new WebResult(errmsg);
                }
                WebResult bwebres = new WebResult();
                string miwen = "";
                WebResult Login_Aspfm_bwr = LoginHelp.Login_Aspfm(miwen);
                if (Login_Aspfm_bwr.Success)
                {
                    bwebres.Result.SetPropertyValue("loginMiwen", miwen);
                    bwebres.Result.SetPropertyValue("loginguid", Login_Aspfm_bwr.Result);
                    return bwebres;
                }
                return Login_Aspfm_bwr;
            }
            return new WebResult("uno_or_logintype_is_null");
        }
        public string SEncryptPwd(string uno, string pwd)
        {
            if (!string.IsNullOrWhiteSpace(uno))
            {
                uno = uno.Trim().ToUpper();
                return MySecurity.SEncryptString(pwd, uno);
            }
            return "";
        }
        public string OnLine()
        {
            if (!string.IsNullOrWhiteSpace(User.LoginGuid))
            {
                string datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                IDbHelper idb = DbFactory.GetDB();
                //是否被强制退出
                string OnLine_exit = PageTool.GetAspfmConfig("系统设置", "OnLine_exit");
                if (!string.IsNullOrWhiteSpace(OnLine_exit) && OnLine_exit == "1")
                {
                    decimal exit = idb.QuerySqlCount("select * from ASPFM_OnLine_exit where loginguid='" + User.LoginGuid + "'");
                    if (exit > 0)
                    {
                        return Logout();
                    }
                }
                //更新最后的存活时间
                AspfmModel dynobj = new AspfmModel();
                dynobj.Values.Add("loginguid", User.LoginGuid);
                dynobj.Values.Add("lastdate", datetime);
                idb.SaveData("ASPFM_OnLine", dynobj, "loginguid");

                //检测最后一次存活时间是在1小时之前的登录信息，并删除
                string lastdatetime = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss");
                DataSet dspage = idb.QueryPage(1, 10, "select loginguid,lastdate from ASPFM_OnLine where lastdate<'" + lastdatetime + "'", "order by loginguid");
                if (DbFactory.CheckDSHadRow(dspage))
                {
                    idb.TransactionBegin();
                    foreach (DataRow dr in dspage.Tables[0].Rows)
                    {
                        string temploginguid = dr["loginguid"].ToString();
                        string lastdate = dr["lastdate"].ToString().Trim();
                        Logout(idb, temploginguid, lastdate);
                    }
                    idb.TransactionClose(true);
                }
                return User.LoginGuid;
            }
            return "";
        }

        private static void Logout(IDbHelper idb, string temploginguid, string lastdate = null)
        {
            if (string.IsNullOrEmpty(lastdate))
            {
                lastdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            idb.ExecSql("update ASPFM_LOG_guid set logoutdate='" + lastdate + "' where loginguid='" + temploginguid + "'");
            idb.ExecSql("delete ASPFM_OnLine where loginguid='" + temploginguid + "'");
        }
        public WebResult OnMsg()
        {
            string strline = OnLine();
            if (strline == "0")
            {
                return new WebResult("The user login at another place。");
            }
            if (!string.IsNullOrWhiteSpace(User._uno))
            {
                IDbHelper idb = DbFactory.GetDB();
                string sql = "select * from ASPFM_SYSMSG msgreceiveid where msgreceiveid='" + User._uno + "' and msgstate=0";
                DataSet dspage = idb.QueryPage(1, 10, sql, "order by msgkey");//一次最多加载10条数据。
                if (DbFactory.CheckDSNotNull(dspage) && dspage.Tables[0].Rows.Count > 0)
                {
                    WebResult bw = new WebResult();
                    bw.WebDataSet = WebDataTable.DataSetToWeb(dspage);
                    bw.AllCount = idb.QuerySqlCount(sql);
                    return bw;
                }
                return new WebResult();
            }
            return new WebResult("uno_is_null");
        }
        public string SetMsgReaded(string msgkey)
        {
            IDbHelper idb = DbFactory.GetDB();
            string strSql = string.Format(" update ASPFM_SYSMSG set msgstate=1 where msgkey='{0}'", msgkey);
            Loger.WriteLog(LogType.WebApp, "查看消息", "msgkey='" + msgkey + "'");
            idb.ExecSql(strSql);
            return "0";
        }
    }
}
